<template>
  <div class="wrap-container">
    <div class="form_cont">
      <template v-if="stepIndex == 0">
        <div class="manage_tit">
          <div class="line"></div>
          <p>场馆实名认证</p>
        </div>
        <el-form
          ref="enterpriseFormRef"
          :model="enterpriseForm"
          :rules="enterpriseRules"
          :hide-required-asterisk="true"
          label-position="left"
          label-width="150px"
        >
          <p class="form_tit">
            <i>*</i>
            <span>主体信息登记</span>
          </p>
          <div class="form_item">
            <el-form-item label="企业类型" prop="enterpriseType" class="enterprise_type">
              <el-radio-group v-model="enterpriseForm.enterpriseType">
                <el-radio
                  v-for="dict in dict?.type?.enterprise_type"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="企业名称" prop="enterpriseName" class="enterprise_name">
              <el-input
                clearable
                class="input_style"
                v-model="enterpriseForm.enterpriseName"
                placeholder="请输入企业名称"
              />
              <p class="form_tips">
                需与当地政府颁发的营业许可证书或企业注册证上的企业名称完全一致，信息审核成功后，企业名称不可修改。
              </p>
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="businessLicenseNum" class="business_name">
              <el-input
                clearable
                class="input_style license_num"
                v-model="enterpriseForm.businessLicenseNum"
                placeholder="请输入统一社会信用代码"
              >
                <template v-slot:append>
                  <el-button type="primary" @click="inputLicenseNum">查询</el-button>
                </template>
              </el-input>
              <p class="form_tips">请输入18位的统一社会信用代码。</p>
            </el-form-item>
            <el-form-item label="工商营业执照" prop="businessImg" class="business_img">
              <p class="form_tips" style="margin-bottom: 8px">
                请上传<span class="blue">最新的营业执照</span>，格式要求：支持 .jpg .jpeg .bmp .gif
                .png格式照片，大小不超过10M。
              </p>
              <upload-img
                v-model="enterpriseForm.businessImg"
                :files="enterpriseForm.businessImg"
                :limit="1"
                @change="changeBusinessImg"
                :size="10"
                ref="businessImgRef"
              />
            </el-form-item>
          </div>
          <div class="flex">
            <div>
              <p class="form_tit">
                <i>*</i>
                <span>认证联系人信息</span>
              </p>
              <div class="form_item">
                <el-form-item label="联系人姓名" prop="contactPerson" class="contact_person">
                  <el-input
                    clearable
                    class="input_style"
                    v-model="enterpriseForm.contactPerson"
                    placeholder="请输入联系人姓名"
                  />
                </el-form-item>
                <el-form-item label="联系人身份证号" prop="contactId" class="contact_id">
                  <el-input
                    clearable
                    class="input_style"
                    v-model="enterpriseForm.contactId"
                    placeholder="请输入联系人身份证号"
                  />
                </el-form-item>
                <el-form-item label="身份证照片" class="contact_img">
                  <p class="form_tips" style="margin-bottom: 8px">
                    请上传联系人身份证原件。保证证件边缘完整、文字清晰、光线均匀。
                  </p>
                  <div class="idCardList">
                    <upload-img
                      v-model="enterpriseForm.contactImg"
                      :files="enterpriseForm.contactImg"
                      :limit="2"
                      :size="10"
                      @change="getCardImgFront"
                      ref="contactImgFrontRef"
                    >
                      <template #upload-button>
                        <div class="card_upload">
                          <p class="upload_add">+</p>
                          <p class="upload_txt">上传图片</p>
                        </div>
                      </template>
                    </upload-img>
                  </div>
                </el-form-item>
                <el-form-item label="联系人电话" prop="contactPhone">
                  <el-input
                    clearable
                    class="input_style"
                    v-model="enterpriseForm.contactPhone"
                    placeholder="请输入联系人电话"
                  >
                  </el-input>
                </el-form-item>
              </div>
            </div>
            <div class="ml-20">
              <p class="form_tit">
                <i>*</i>
                <span>对公账户信息</span>
              </p>
              <div class="form_item">
                <el-form-item label="开户名称" prop="accountName" class="account_info">
                  <el-input
                    clearable
                    class="input_style"
                    v-model="enterpriseForm.accountName"
                    placeholder="请输入开户名称"
                  />
                </el-form-item>
                <el-form-item label="开户银行" prop="accountBank" class="account_info">
                  <el-input
                    clearable
                    class="input_style"
                    v-model="enterpriseForm.accountBank"
                    placeholder="请输入开户银行"
                  />
                </el-form-item>
                <el-form-item label="银行账号" prop="accountBankNumber" class="account_info">
                  <el-input
                    clearable
                    class="input_style"
                    v-model="enterpriseForm.accountBankNumber"
                    placeholder="请输入银行账号"
                  />
                </el-form-item>
              </div>
              <div class="contract_form">
                <p class="form_tit">
                  <i>*</i>
                  <span>上传合同</span>
                </p>
                <div class="form_item">
                  <el-form-item label-width="0" prop="pactImg">
                    <p class="align_center">
                      请拍照上传加盖公章的合同原件或电子合同
                      <span
                        class="align_center"
                        @click="downloadFile"
                        style="margin-left: 10px; color: #0988fb; cursor: pointer"
                        v-if="enterpriseForm.contractFile.length > 0"
                        ><img src="@/assets/images/icon/download_icon.png" />下载合同</span
                      >
                    </p>
                    <upload-img
                      v-model="enterpriseForm.contractFile"
                      :files="enterpriseForm.contractFile"
                      :limit="1"
                      :accept="'.pdf'"
                      list-type="text"
                      :size="10"
                      file-type="file"
                      @change="getContractFile"
                      ref="contractFileRef"
                      class="contract_file"
                    />
                    <div class="upload_contract">
                      <upload-img
                        :limit="100"
                        :size="10"
                        @change="getContractImg"
                        v-model="enterpriseForm.contractImg"
                        :files="enterpriseForm.contractImg"
                        ref="contractImgRef"
                      >
                        <template #upload-button>
                          <div class="upload_btn">
                            <p class="upload_add">+</p>
                            <p class="upload_txt">上传图片</p>
                          </div>
                        </template>
                      </upload-img>
                    </div>
                  </el-form-item>
                </div>
              </div>
              <el-form-item label="上级公司" prop="deptId" style="margin-left: 20px">
                <el-cascader
                  filterable
                  clearable
                  :options="deptList"
                  :props="{ checkStrictly: true }"
                  v-model="enterpriseForm.deptId"
                  class="input_style"
                ></el-cascader>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div class="form_btn">
          <el-button @click="handleCancel" class="default_btn">取消</el-button>
          <el-button @click="() => handleSaveOne()" class="default_btn warn">保存</el-button>
          <el-button @click="() => handleSaveOne(1)" class="default_btn primary">下一步</el-button>
        </div>
      </template>
      <template v-else>
        <div class="manage_tit">
          <div class="line"></div>
          <p>场馆信息编辑</p>
        </div>
        <div class="stadium_box">
          <el-form
            ref="stadiumFormRef"
            :model="stadiumForm"
            :rules="stadiumRules"
            label-position="left"
            label-width="110px"
            class="stadium_form"
          >
            <el-tabs v-model="activeName" @tab-change="handleTabsClick">
              <el-tab-pane label="基本设置" name="1">
                <div class="form_item">
                  <el-form-item label="门店名称" prop="stadiumName">
                    <el-input clearable class="input_style" v-model="stadiumForm.stadiumName" />
                  </el-form-item>
                  <el-form-item label="场馆类型" prop="stadiumType">
                    <el-select
                      filterable
                      clearable
                      v-model="stadiumForm.stadiumType"
                      class="input_style"
                      @change="changeStadiumType"
                    >
                      <el-option
                        v-for="item in dictTypeList"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item class="business_item">
                    <template v-slot:label>
                      <span><i style="margin-right: 4px; color: #ff4949">*</i>营业时间 </span>
                    </template>
                    <el-form-item label="周一至周日">
                      <div class="align_center">
                        <el-form-item prop="workDateStart">
                          <el-time-select
                            clearable
                            v-model="stadiumForm.workDateStart"
                            :picker-options="{
                              start: '00:00',
                              step: '00:60',
                              end: '24:00',
                              maxTime: stadiumForm.workDateEnd,
                            }"
                            style="width: 116px; margin-right: 18px"
                          >
                          </el-time-select>
                        </el-form-item>
                        <el-form-item prop="workDateEnd">
                          <el-time-select
                            clearable
                            v-model="stadiumForm.workDateEnd"
                            :picker-options="{
                              start: '00:00',
                              step: '00:60',
                              end: '24:00',
                              minTime: stadiumForm.workDateStart,
                            }"
                            style="width: 116px"
                          >
                          </el-time-select>
                        </el-form-item>
                      </div>
                    </el-form-item>
                    <el-form-item label="节假日">
                      <div class="align_center">
                        <el-form-item prop="legalDateStart">
                          <el-time-select
                            clearable
                            v-model="stadiumForm.legalDateStart"
                            :picker-options="{
                              start: '00:00',
                              step: '00:60',
                              end: '24:00',
                              maxTime: stadiumForm.legalDateEnd,
                            }"
                            style="width: 116px; margin-right: 18px"
                          >
                          </el-time-select>
                        </el-form-item>
                        <el-form-item prop="legalDateEnd">
                          <el-time-select
                            clearable
                            v-model="stadiumForm.legalDateEnd"
                            :picker-options="{
                              start: '00:00',
                              step: '00:60',
                              end: '24:00',
                              minTime: stadiumForm.legalDateStart,
                            }"
                            style="width: 116px"
                          >
                          </el-time-select>
                        </el-form-item>
                      </div>
                    </el-form-item>
                  </el-form-item>
                  <el-form-item label="门店电话" prop="phone">
                    <el-input clearable class="input_style" v-model="stadiumForm.phone" />
                  </el-form-item>
                  <el-form-item label="门店地址" prop="addressId">
                    <el-cascader
                      filterable
                      clearable
                      :options="areaTree"
                      v-model="stadiumForm.addressId"
                      @change="handleChange"
                      style="width: 230px"
                    ></el-cascader>
                  </el-form-item>
                  <el-form-item prop="address">
                    <el-input
                      clearable
                      v-model="stadiumForm.address"
                      class="input_style"
                      @input="handleInput"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="所属企业">
                    <el-input
                      clearable
                      class="input_style"
                      disabled
                      v-model="enterpriseForm.enterpriseName"
                    />
                  </el-form-item>
                </div>
              </el-tab-pane>
              <el-tab-pane label="场馆设施 " name="2">
                <div class="form_item service_item">
                  <el-form-item
                    label="场馆服务"
                    prop="selectService"
                    class="default_price stadium_service"
                  >
                    <el-checkbox-group v-model="stadiumForm.selectService">
                      <el-checkbox
                        :label="item.raw.dictCode"
                        v-for="item in dict?.type?.service_type"
                        :key="item.raw.dictCode"
                      >
                        <span>{{ item.label }}</span>
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item label="场馆标签" prop="stadiumLabelList">
                    <div class="flex stadium_label" style="width: 603px">
                      <div class="flex stadium_label_box flex-wrap">
                        <div
                          v-for="(ele, idx) in stadiumForm.stadiumLabelList"
                          :key="idx"
                          class="flex label_item justify-between items-center"
                        >
                          <span>{{ ele }}</span>
                          <img
                            src="@/assets/images/icon/del_blue.png"
                            @click="delStadiumLabel(idx)"
                            class="cursor-pointer"
                          />
                        </div>
                      </div>
                      <el-input clearable v-model="stadiumLabel" @blur="stadiumLabelBlur">
                        <!-- <template slot="append">
                          <span class="text-xs">最多可支持4个标签</span>
                        </template> -->
                      </el-input>
                      <p class="text-xs">最多可支持4个标签</p>
                    </div>
                  </el-form-item>
                </div>
              </el-tab-pane>
              <el-tab-pane label="图片管理 " name="3">
                <div class="form_item imgs_item" style="margin-top: 13px">
                  <el-form-item label="添加头像" prop="headImg">
                    <upload-img
                      :limit="1"
                      :multiple="true"
                      :default-one="true"
                      :accept="'.jpg,.png'"
                      :size="2"
                      ref="headImgRef"
                      @change="getStadiumHeadImg"
                      key="imgStr"
                    >
                      <template #upload-button>
                        <div class="upload_img">
                          <p class="upload_txt">+上传图片</p>
                          <p class="tips_img" style="margin-top: 16px">
                            支持jpg/png，大小在2MB以内
                          </p>
                        </div>
                      </template>
                    </upload-img>
                  </el-form-item>
                  <el-form-item label="场馆相册" prop="imgStr">
                    <upload-img
                      :limit="100"
                      :multiple="true"
                      :default-one="true"
                      :accept="'.jpg,.png'"
                      :size="2"
                      ref="stadiumImgRef"
                      @change="getStadiumImg"
                      key="imgStr"
                    >
                      <template #upload-button>
                        <div class="upload_img">
                          <p class="upload_txt">+上传图片</p>
                          <p class="tips_img" style="margin-top: 16px">
                            支持jpg/png，大小在2MB以内
                          </p>
                        </div>
                      </template>
                    </upload-img>
                  </el-form-item>
                  <el-form-item label="场馆平面图">
                    <upload-img
                      :limit="100"
                      :multiple="true"
                      ref="siteLocationRef"
                      @change="getSiteLocation"
                      key="siteLocation"
                    >
                      <template #upload-button>
                        <div class="upload_img">
                          <p class="upload_txt">+上传图片</p>
                          <p class="tips_img" style="margin-top: 16px">
                            支持jpg/png，大小在2MB以内
                          </p>
                        </div>
                      </template>
                    </upload-img>
                  </el-form-item>
                </div>
              </el-tab-pane>
              <el-tab-pane label="规则设置" name="4">
                <div class="form_item rules_item">
                  <el-form-item label="默认价格" prop="isDefaultPrice" class="default_price">
                    <el-radio-group v-model="stadiumForm.isDefaultPrice">
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="退款时限 " prop="cancelHours" class="cancel_hours">
                    <el-input
                      clearable
                      type="number"
                      v-model="stadiumForm.cancelHours"
                      class="input_style"
                    >
                      <template v-slot:append>小时</template></el-input
                    >
                  </el-form-item>
                  <el-form-item label="退款说明" prop="cancelRule" class="cancel_rule">
                    <el-input
                      clearable
                      v-model="stadiumForm.cancelRule"
                      type="textarea"
                      :rows="6"
                      class="input_style"
                    />
                  </el-form-item>
                  <el-form-item label="提前核销时间" prop="writeMinutes">
                    <el-input
                      clearable
                      type="number"
                      v-model="stadiumForm.writeMinutes"
                      class="input_style"
                    >
                      <template v-slot:append>分钟</template></el-input
                    >
                  </el-form-item>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </div>

        <div class="form_btn">
          <el-button class="default_btn" @click="handlePrevStep">上一步</el-button>
          <el-button class="default_btn warn" @click="() => handleSubmit(1)">保存</el-button>
          <el-button @click="handleNextStep" class="default_btn primary" v-if="activeName != '4'"
            >下一步</el-button
          >
          <el-button @click="() => handleSubmit(2)" class="default_btn primary" v-else
            >提交审核</el-button
          >
        </div>
      </template>
    </div>
    <approval-dialog ref="approvalDialogRef" @sure="goJumpPage"></approval-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  createStadium,
  getAreaTree,
  getEnterpriseData as getEnterpriseDataApi,
  getEnterpriseDataByNum,
  settingStadiumInfo,
  getStadiumApprovalData,
} from '@/api/stadium/stadium'
import { listData } from '@/api/system/dict/data'
import { deptTreeSelect } from '@/api/system/user'
import uploadImg from '@/components/Upload/uploadImg.vue'
import approvalDialog from '@/components/Approval/approvalDialog.vue'
import { useDict } from '@/utils/dict'
import { ElMessage, ElMessageBox, type FormInstance, type UploadFile } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { debounce } from 'lodash'
import type { CascaderOption, CascaderProps, TabPaneName } from 'element-plus'

interface DictItem {
  value: string
  label: string
  raw: {
    dictCode: string
  }
}

interface Dict {
  type: {
    enterprise_type: DictItem[]
    service_type: DictItem[]
  }
}

interface DictTypeItem {
  dictValue: string
  dictLabel: string
}

interface EnterpriseForm {
  id: number | null
  enterpriseType: string
  enterpriseName: string
  businessLicenseNum: string
  businessImg: string | null
  contactPerson: string
  contactPhone: string
  contactId: string
  contactImg: string
  accountName: string
  accountBank: string
  accountBankNumber: string
  pactImg: string
  contractFile: UploadFile[]
  contractImg: UploadFile[]
  deptId: number[] | null
  dataFlag: number | null
}

interface StadiumForm {
  headImg: string | null
  imgStr: string | null
  siteLocation: string | null
  stadiumName: string | null
  stadiumType: string | null
  phone: string | null
  address: string | null
  stateId: number | null
  cityId: number | null
  districtId: number | null
  workDateStart: string | null
  workDateEnd: string | null
  legalDateStart: string | null
  legalDateEnd: string | null
  addressId: (number | null)[]
  selectService: number[]
  dictIdStr: string | null
  isDefaultPrice: number
  cancelHours: string | null
  cancelRule: string | null
  writeMinutes: string | null
  stadiumLabel: string | null
  stadiumLabelList: string[]
  imgList?: any[]
  gdAddress?: string
  modifyContent?: string | number
  id?: number
  dataFlag?: number | null
}

interface AreaTreeItem {
  value: number
  label: string
  children?: AreaTreeItem[]
}

interface DeptListItem {
  id: number
  label: string
  value: number
  disabled?: boolean
  children?: DeptListItem[]
}

const route = useRoute()
const router = useRouter()

const { dict } = useDict({
  dicts: ['enterprise_type', 'service_type'],
})

const stepIndex = ref(0)
const areaTree = ref<AreaTreeItem[]>([])
const dictTypeList = ref<DictTypeItem[]>([])
const siteTypeList = ref<DictTypeItem[]>([])
const deptList = ref<DeptListItem[]>([])
const activeName = ref('1')
const stadiumLabel = ref<string | null>(null)

const enterpriseFormRef = ref<FormInstance | null>(null)
const stadiumFormRef = ref<FormInstance | null>(null)
const businessImgRef = ref<InstanceType<typeof uploadImg> | null>(null)
const contactImgFrontRef = ref<InstanceType<typeof uploadImg> | null>(null)
const contractFileRef = ref<InstanceType<typeof uploadImg> | null>(null)
const contractImgRef = ref<InstanceType<typeof uploadImg> | null>(null)
const headImgRef = ref<InstanceType<typeof uploadImg> | null>(null)
const stadiumImgRef = ref<InstanceType<typeof uploadImg> | null>(null)
const siteLocationRef = ref<InstanceType<typeof uploadImg> | null>(null)
const approvalDialogRef = ref<InstanceType<typeof approvalDialog> | null>(null)

const enterpriseForm = reactive<EnterpriseForm>({
  id: null,
  enterpriseType: '',
  enterpriseName: '',
  businessLicenseNum: '',
  businessImg: null,
  contactPerson: '',
  contactPhone: '',
  contactId: '',
  contactImg: '',
  accountName: '',
  accountBank: '',
  accountBankNumber: '',
  pactImg: '',
  contractFile: [],
  contractImg: [],
  deptId: null,
  dataFlag: null,
})

const stadiumForm = reactive<StadiumForm>({
  headImg: null,
  imgStr: null,
  siteLocation: null,
  stadiumName: null,
  stadiumType: null,
  phone: null,
  address: null,
  stateId: null,
  cityId: null,
  districtId: null,
  workDateStart: null,
  workDateEnd: null,
  legalDateStart: null,
  legalDateEnd: null,
  addressId: [],
  selectService: [],
  dictIdStr: null,
  isDefaultPrice: 1,
  cancelHours: null,
  cancelRule: null,
  writeMinutes: null,
  stadiumLabel: null,
  stadiumLabelList: [],
})

const enterpriseRules = {
  enterpriseType: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
  enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  businessLicenseNum: [
    {
      required: true,
      message: '请输入统一社会信用代码',
      trigger: 'blur',
    },
  ],
  businessImg: [
    {
      required: true,
      message: '请上传工商营业执照',
      trigger: 'change',
    },
  ],
  contactPerson: [
    {
      required: true,
      message: '请输入联系人姓名',
      trigger: 'blur',
    },
  ],
  contactId: [
    {
      required: true,
      message: '请输入联系人身份证号',
      trigger: 'blur',
    },
  ],
  contactPhone: [
    {
      required: true,
      message: '请输入联系人电话',
      trigger: 'blur',
    },
  ],
  accountName: [
    {
      required: true,
      message: '请输入开户名称',
      trigger: 'blur',
    },
  ],
  accountBank: [
    {
      required: true,
      message: '请输入开户银行',
      trigger: 'blur',
    },
  ],
  accountBankNumber: [
    {
      required: true,
      message: '请输入银行账号',
      trigger: 'blur',
    },
  ],
  pactImg: [
    {
      required: true,
      message: '请上传合同',
      trigger: 'change',
    },
  ],
  deptId: [{ required: true, message: '请选择归属公司', trigger: 'change' }],
}

const stadiumRules = {
  stadiumName: [
    {
      required: true,
      message: '请输入门店名称',
      trigger: 'blur',
    },
  ],
  headImg: [
    {
      required: true,
      message: '请上传头像',
      trigger: 'change',
    },
  ],
  imgStr: [
    {
      required: true,
      message: '请上传场馆图片',
      trigger: 'change',
    },
  ],
  stadiumType: [
    {
      required: true,
      message: '请选择场馆类型',
      trigger: 'change',
    },
  ],
  workDateStart: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  workDateEnd: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  legalDateStart: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  legalDateEnd: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入门店电话',
      trigger: 'blur',
    },
  ],
  addressId: [
    {
      required: true,
      message: '请选择省市区',
      trigger: 'change',
    },
  ],
  address: [
    {
      required: true,
      message: '请输入详细地址',
      trigger: 'blur',
    },
  ],
  selectService: [
    {
      required: true,
      message: '请选择场馆服务',
      trigger: 'change',
    },
  ],
  stadiumLabelList: [
    {
      required: true,
      message: '请输入场馆标签',
      trigger: 'change',
    },
  ],
  isDefaultPrice: [
    {
      required: true,
      message: '请选择是否设置默认价格',
      trigger: 'change',
    },
  ],
  cancelHours: [
    {
      required: true,
      message: '请输入退款规则',
      trigger: 'blur',
    },
  ],
  cancelRule: [
    {
      required: true,
      message: '请输入退款说明',
      trigger: 'blur',
    },
  ],
  writeMinutes: [
    {
      required: true,
      message: '请输入提前核销时间限制',
      trigger: 'blur',
    },
  ],
}

//获取场馆类型
const getDictTypeList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 99,
    dictType: 'site_type',
  }
  const res: any = await listData(params)
  dictTypeList.value = res.rows
  dictTypeList.value.unshift({ dictValue: '0', dictLabel: '综合' })
}

/** 查询部门列表 */
const getDeptList = () => {
  deptTreeSelect().then((response: any) => {
    deptList.value = formatToCascaderData(response.data)
    if (enterpriseForm.deptId == null && deptList.value.length > 0) {
      const firstValue = deptList?.value[0]?.value
      if (firstValue !== undefined) {
        enterpriseForm.deptId = [firstValue]
      }
    }
  })
}

//数据处理为兼容cascader数据格式
const formatToCascaderData = (rawData: any[]): DeptListItem[] => {
  const processNode = (node: any): DeptListItem | null => {
    if (!node) return null

    return {
      value: node.id, // 使用 id 作为 value
      label: node.label, // 显示文本
      disabled: node.disabled, // 禁用状态
      children: node.children ? node.children.map(processNode) : undefined,
    } as DeptListItem
  }

  // 处理可能的顶层数组嵌套
  return rawData
    .map((item) => {
      if (item.children) {
        return processNode(item)
      }
      return {
        value: item.id,
        label: item.label,
        disabled: item.disabled,
      } as DeptListItem
    })
    .filter(Boolean) as DeptListItem[] // 过滤空节点
}

// 获取企业认证信息
const getEnterpriseData = async () => {
  if (enterpriseForm.id === null) return

  const res: any = await getEnterpriseDataApi({
    stadiumId: enterpriseForm.id,
  })
  if (res.data) {
    const enterpriseData = res.data
    handleEnterpriseData(enterpriseData)
  }
}

// 处理企业认证信息的回显
const handleEnterpriseData = (enterpriseData: any, type?: number) => {
  for (const key in enterpriseData) {
    if (Object.prototype.hasOwnProperty.call(enterpriseForm, key)) {
      ;(enterpriseForm as any)[key] = enterpriseData[key]
    }
  }
  const refBusiness = businessImgRef.value
  const imgBusiness = enterpriseForm.businessImg?.split(',') ?? []
  if (refBusiness) {
    refBusiness.fileList = imgBusiness.map((url) => ({
      name: '已上传图片',
      url: url,
    })) as UploadFile[]
  }

  const refFront = contactImgFrontRef.value
  const imgFront = enterpriseForm.contactImg?.split(',').filter(Boolean) ?? []
  if (refFront) {
    refFront.fileList = imgFront.map((url) => ({
      name: '已上传图片',
      url: url,
    })) as UploadFile[]
  }

  const pactImgArr = enterpriseData?.pactImg?.split(',') ?? []
  if (enterpriseData.pactName != '' && enterpriseData.pactName != null) {
    const files = pactImgArr[0]
    enterpriseForm.contractFile = [{ name: enterpriseData.pactName, url: files } as UploadFile]
    enterpriseForm.contractImg = pactImgArr.slice(1).map(
      (url: string) =>
        ({
          name: '已上传图片',
          url: url,
        }) as UploadFile,
    )
  } else {
    enterpriseForm.contractImg = pactImgArr.map(
      (url: string) =>
        ({
          name: '已上传图片',
          url: url,
        }) as UploadFile,
    )
  }

  const refFile = contractFileRef.value
  if (refFile) {
    refFile.fileList = enterpriseForm.contractFile
  }

  const refImg = contractImgRef.value
  if (refImg) {
    refImg.fileList = enterpriseForm.contractImg
  }

  if (type == 1) {
    enterpriseForm.id = null
  }
}

// 获取工商营业执照
const changeBusinessImg = (data: UploadFile[]) => {
  enterpriseForm.businessImg = data.map((item) => item.url).join(',')
  enterpriseFormRef.value?.clearValidate('businessImg')
}

// 获取合同文件
const getContractFile = (data: UploadFile[]) => {
  enterpriseForm.contractFile = data as UploadFile[]
  enterpriseFormRef.value?.clearValidate('pactImg')
}

// 获取合同图片
const getContractImg = (data: UploadFile[]) => {
  enterpriseForm.contractImg = data as UploadFile[]
  enterpriseFormRef.value?.clearValidate('pactImg')
}

// 获取身份证正面图片
const getCardImgFront = (data: UploadFile[]) => {
  enterpriseForm.contactImg = data.map((item) => item.url).join(',')
  enterpriseFormRef.value?.clearValidate('contactImg')
}

// 获取场馆信息
const getStadium = async () => {
  if (enterpriseForm.id === null) return

  const { data } = await getStadiumApprovalData(enterpriseForm.id)
  Object.assign(stadiumForm, data.stadiumBaseData)
  stadiumForm.dataFlag = enterpriseForm.dataFlag
  const addressId =
    stadiumForm.stateId != null
      ? [stadiumForm.stateId, stadiumForm.cityId, stadiumForm.districtId]
      : [null, null, null]
  stadiumForm.addressId = addressId
  stadiumForm.selectService = data.serviceList.map((item: any) => item.dictId) || []
  stadiumForm.stadiumLabelList = stadiumForm.stadiumLabel?.split(',') || []

  const imgArr: any[] = []
  data.imgList.map((item: any) => {
    const obj = {
      uid: item.imgId,
      id: item.imgId,
      url: item.imgUrl,
    }
    imgArr.push(obj)
  })
  stadiumForm.imgList = imgArr

  // 使用 nextTick 确保 DOM 更新后再执行
  setTimeout(() => {
    const headImgRefValue = headImgRef.value
    const imgHeadImg = stadiumForm.headImg?.split(',').filter(Boolean) || []
    if (headImgRefValue) {
      headImgRefValue.fileList = imgHeadImg.map(
        (url) =>
          ({
            name: '已上传图片',
            url: url,
          }) as UploadFile,
      )
    }

    const stadiumImgRefValue = stadiumImgRef.value
    if (stadiumImgRefValue) {
      stadiumImgRefValue.fileList = stadiumForm.imgList || []
    }

    const siteLocationRefValue = siteLocationRef.value
    const imgSiteLocation = stadiumForm.siteLocation?.split(',').filter(Boolean) || []
    if (siteLocationRefValue) {
      siteLocationRefValue.fileList = imgSiteLocation.map(
        (url) =>
          ({
            name: '已上传图片',
            url: url,
          }) as UploadFile,
      )
    }
  }, 0)

  setTimeout(() => {
    stadiumFormRef.value?.clearValidate()
  }, 0)
}

//监听场馆详细地址 高德查询坐标
const handleInput = () => {
  const state = stadiumForm.addressId[0]
  const city = stadiumForm.addressId[1]
  const district = stadiumForm.addressId[2]
  const gdAddress = stadiumForm.address
  if (stadiumForm.addressId == null) {
    ElMessage({
      message: '请选择门店地址！',
      type: 'error',
    })
  } else {
    let stateName = '',
      cityName = '',
      districtName = ''
    areaTree.value.forEach((item) => {
      if (item.value == state) {
        stateName = item.label
      }
      item.children?.forEach((cityItem) => {
        if (cityItem.value == city) {
          cityName = cityItem.label
        }
        cityItem.children?.forEach((districtItem) => {
          if (districtItem.value == district) {
            districtName = districtItem.label
          }
        })
      })
    })
    stadiumForm.gdAddress =
      stateName == cityName
        ? `${stateName}${districtName}${gdAddress}`
        : `${stateName}${cityName}${districtName}${gdAddress}`
  }
}

// 选择场馆类型 联动场地类型
const changeStadiumType = (val: string) => {
  if (val == '0') {
    siteTypeList.value = dictTypeList.value.slice(1)
  } else {
    const typeName = dictTypeList.value.find((item) => item.dictValue == val)?.dictLabel
    if (typeName) {
      siteTypeList.value = [{ dictLabel: typeName, dictValue: val }]
    }
  }
}

// 获取省市区数据
const getArea = () => {
  getAreaTree().then((res: any) => {
    areaTree.value = res.data
  })
}

// 省市区选择
const handleChange = (value: any) => {
  if (Array.isArray(value) && value.length >= 3) {
    stadiumForm.stateId = value[0] ?? null
    stadiumForm.cityId = value[1] ?? null
    stadiumForm.districtId = value[2] ?? null
    handleInput()
  }
}

// 获取场馆头像
const getStadiumHeadImg = (data: UploadFile[]) => {
  stadiumForm.headImg = data.map((item) => item.url).join(',')
  stadiumFormRef.value?.clearValidate('headImg')
}

// 获取场馆图片
const getStadiumImg = (data: UploadFile[]) => {
  stadiumForm.imgStr = data.map((item) => item.url).join(',')
  stadiumFormRef.value?.clearValidate('imgStr')
}

// 获取场馆平面图
const getSiteLocation = (data: UploadFile[]) => {
  stadiumForm.siteLocation = data.map((item) => item.url).join(',')
  stadiumFormRef.value?.clearValidate('siteLocation')
}

// 场馆标签失去焦点
const stadiumLabelBlur = () => {
  if (stadiumLabel.value != '' && stadiumLabel.value != null) {
    if (stadiumForm.stadiumLabelList.length == 4) {
      ElMessage.error('最多可支持4个标签')
      return
    }
    stadiumForm.stadiumLabelList.push(stadiumLabel.value)
    stadiumLabel.value = null
  }
  stadiumFormRef.value?.clearValidate(['stadiumLabel'])
}

// 删除场馆标签
const delStadiumLabel = (index: number) => {
  stadiumForm.stadiumLabelList.splice(index, 1)
}

// 取消返回上一页
const handleCancel = () => {
  router.go(-1)
}

// 第一步企业信息保存
const handleSaveOne = debounce(
  (index?: number) => {
    try {
      let pactImg = ''
      if (enterpriseForm.contractFile.length > 0) {
        ;(enterpriseForm as any).pactName = enterpriseForm?.contractFile?.[0]?.name
        pactImg = enterpriseForm.contractFile.map((item) => item.url).join(',') || ''
      }
      if (enterpriseForm.contractImg.length > 0) {
        pactImg =
          (pactImg != '' ? pactImg + ',' : '') +
          enterpriseForm.contractImg.map((item) => item.url).join(',')
      }
      enterpriseForm.pactImg = pactImg
      const enterpriseParams = JSON.parse(JSON.stringify(enterpriseForm))
      if (enterpriseParams.deptId != null && Array.isArray(enterpriseParams.deptId)) {
        enterpriseParams.deptId = enterpriseParams.deptId.slice(-1)[0]
      }
      enterpriseFormRef.value?.validate(async (valid, obj) => {
        if (valid) {
          const res: any = await createStadium(enterpriseParams)
          enterpriseForm.id = res.data
          ElMessage.success(res.msg)
          getDeptList()
          getEnterpriseData()
          if (index == 1) {
            stepIndex.value = index
            getStadium()
          }
        } else {
          // for (let key in obj) {
          //   ElMessage.error(obj[key][0].message);
          //   return;
          // }
        }
      })
    } catch (e) {
      ElMessage.error((e as Error)?.message || '请求失败，请稍后再试')
    }
  },
  1000,
  { leading: true, trailing: false },
)

// 暂存场馆基本信息
const saveStadium = async (type: number) => {
  if (enterpriseForm.id !== null) {
    stadiumForm.id = enterpriseForm.id
  }
  stadiumForm.modifyContent = activeName.value
  stadiumForm.dictIdStr = stadiumForm.selectService?.join(',')
  stadiumForm.stadiumLabel = stadiumForm.stadiumLabelList?.join(',')
  if (type == 2) {
    stadiumForm.modifyContent = 5
  }
  await settingStadiumInfo(stadiumForm)
  if (type != 2) {
    ElMessage.success('操作成功')
  }
}

// 场馆基本信息提交审核
const handleSubmit = debounce(
  (type: number) => {
    try {
      if (type == 1) {
        saveStadium(type)
      } else {
        stadiumFormRef.value?.validate(async (valid, obj) => {
          if (valid) {
            await saveStadium(type)
            if (approvalDialogRef.value) {
              approvalDialogRef.value.approvalVisible = true
            }
          } else {
            for (const key in obj) {
              if (obj[key] && obj[key][0]) {
                ElMessage.error(obj[key][0].message)
              }
              return
            }
          }
        })
      }
    } catch (e) {
      ElMessage.error((e as Error)?.message || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 上一步
const handlePrevStep = () => {
  if (activeName.value == '1') {
    stepIndex.value = 0
    getEnterpriseData()
    return
  }
  const currentName = Number(activeName.value)
  activeName.value = (currentName - 1).toString()
}

// 下一步
const handleNextStep = async () => {
  await saveStadium(0)
  const currentName = Number(activeName.value)
  activeName.value = (currentName + 1).toString()
}

// 合同下载
const downloadFile = async () => {
  if (enterpriseForm.contractFile.length === 0) return

  const file = enterpriseForm.contractFile[0]
  if (!file || !file.url) return

  const url = file.url
  const fileName = file.name
  const response = await fetch(url)
  const blob = await response.blob()
  const link = document.createElement('a')
  link.href = window.URL.createObjectURL(blob)
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 监听输入统一社会信用代码
const inputLicenseNum = async () => {
  // 校验businessLicenseNum是否为空
  if (!enterpriseForm.businessLicenseNum) {
    ElMessage.error('请输入统一社会信用代码')
    return
  }
  const res: any = await getEnterpriseDataByNum({
    businessLicenseNum: enterpriseForm.businessLicenseNum,
  })
  if (res.data) {
    ElMessageBox.confirm(
      '该社会信用代码下已存在企业认证信息，是否使用并替换掉已填写的企业信息',
    ).then(() => {
      handleEnterpriseData(res.data, 1)
    })
  } else {
    ElMessage('该社会信用代码下无企业信息')
  }
}

// 场馆信息编辑tabs切换
const handleTabsClick = (tabName: TabPaneName) => {
  // 可以在这里添加切换tab时的逻辑
}

// 提交审核跳转页面
const goJumpPage = () => {
  router.push({ path: '/stadium/list' })
}

onMounted(() => {
  getDictTypeList()
  getDeptList()
  getEnterpriseData()
  getArea()
})
</script>

<style lang="scss" scoped>
.form_cont {
  background: #fff;
  padding: 15px 15px 36px;
  height: 100%;
  overflow-y: auto;
  position: relative;
  :deep(.el-form) {
    .form_tit {
      font-size: 14px;
      line-height: 21px;
      margin: 20px 0 8px 13px;
      i {
        color: #d43030;
        margin-right: 2px;
      }
    }
    .form_item {
      padding-left: 20px;
    }
    .el-form-item {
      margin-bottom: 22px;
      &.enterprise_type {
        margin-bottom: 5px;
      }
      &.enterprise_name {
        margin-bottom: 16px;
      }
      &.business_name {
        margin-bottom: 13px;
      }
      &.business_img {
        margin-bottom: 4px;
      }
      &.contact_person {
        margin-bottom: 38px;
      }
      &.contact_id {
        margin-bottom: 30px;
      }
      &.account_info {
        margin-bottom: 15px;
      }
      p {
        color: #808080;
        font-size: 12px;
        line-height: 18px;
      }
    }
    .el-form-item__label {
      font-weight: normal;
      color: #383838;
    }
    .el-form-item__content .input_style {
      width: 501px;
      height: 35px;
      .el-button {
        background: #f5f7f9;
        margin: 0 -20px;
        font-size: 12px;
        color: #a6a6a6;
        padding: 0 29px;
      }
    }
    &.stadium_form {
      .form_item {
        margin-top: 11px;
        padding-left: 99px;
      }
      .el-form-item__label {
        height: 30px;
        line-height: 32px;
      }
      .el-input__inner {
        height: 30px;
        line-height: 30px;
      }
      .el-form-item {
        margin-bottom: 20px;
        &.cancel_rule {
          margin-bottom: 16px;
        }
        &.cancel_hours {
          margin-bottom: 10px;
        }
        &.stadium_service {
          .el-form-item__error {
            top: 30px;
          }
        }
      }
      .business_item {
        .el-form-item {
          margin-bottom: 14px;
          & + .el-form-item {
            margin-bottom: 0;
          }
        }
      }
      .el-form-item__content .input_style {
        width: 397px;
        height: auto;
      }
      .default_price {
        &.el-form-item {
          margin-bottom: 13px;
        }
        .el-form-item__content {
          line-height: 30px;
        }
      }
      .el-input-group__append {
        padding: 0 17px;
        color: #a6a6a6;
        background: #f5f5f5;
      }
      .imgs_item {
        .el-form-item {
          margin-bottom: 16px;
        }
      }
      .service_item {
        margin-top: 7px;
        .el-input-group--append {
          .el-input__inner {
            border-right: none;
          }
          .el-input-group__append {
            background: none;
          }
        }
        .el-input__inner:focus {
          border-color: #a6a6a6;
        }
      }
      .stadium_label {
        width: 100%;
        min-height: 30px;
        border: 1px solid #a6a6a6;
        border-radius: 3px;
        box-sizing: border-box;
        position: relative;
        .el-input {
          flex: 1;
          height: 30px;
          line-height: 30px;
          .el-input__inner {
            border: none;
            background: none;
            height: 25px;
          }
          .el-input-group__append {
            border: none;
          }
        }
        .stadium_label_box {
          max-width: 400px;
          .label_item {
            padding: 0 10px 0 9px;
            height: 21px;
            line-height: 21px;
            background: #dae6f9;
            border-radius: 66px;
            font-size: 12px;
            color: #0988fb;
            margin-left: 12px;
            margin-top: 5px;
          }
          img {
            width: 8px;
            height: 8px;
            margin-left: 10px;
          }
        }
        p {
          position: absolute;
          right: 16px;
          top: 7px;
          font-size: 12px;
          line-height: 18px;
        }
      }
      .upload-demo .el-upload-list--picture-card .el-upload-list__item {
        width: 107px;
        height: 100px;
        border-radius: 0;
      }
    }
    .idCardList {
      display: flex;
      .el-upload-list--picture-card .el-upload-list__item {
        width: 156px;
        height: 99px;
        margin-right: 24px;
      }
    }
    .card_upload {
      width: 156px;
      height: 99px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      margin-right: 24px;
      p {
        font-size: 14px;
        color: #a6a6a6;
        line-height: 21px;
        &.upload_add {
          font-size: 48px;
          margin-top: 24px;
        }
        &.upload_txt {
          margin-top: 10px;
        }
      }
    }
    .upload_img {
      padding: 0 6px 0 7px;
      width: 107px;
      height: 100px;
      border: 1px solid #dcdfe6;
      .tips_img {
        font-size: 10px !important;
        color: #a6a6a6;
        line-height: 15px;
        margin-top: 6px;
      }
      .upload_txt {
        font-size: 13px !important;
        color: #2a82e4 !important;
        line-height: 21px;
        margin-top: 17px;
      }
    }
    .contract_form {
      display: flex;
      .form_tit {
        width: 150px;
        margin-top: 11px;
      }
      .form_item {
        margin-top: 11px;
        padding-left: 7px;
        p {
          font-size: 12px;
          color: #808080;
          line-height: 18px;
          margin-bottom: 9px;
        }
      }
      .el-form-item {
        margin-bottom: 0;
      }
    }
    .form_tips {
      line-height: normal;
      margin-top: 10px;
    }
    .business_img {
      .el-upload-list--picture-card .el-upload-list__item {
        width: 150px;
        height: 110px;
      }
    }
    .upload_contract {
      margin-top: 10px;
      .el-upload-list--picture-card .el-upload-list__item {
        width: 150px;
        height: 110px;
        margin-right: 17px;
      }
    }
    .upload_btn {
      width: 110px;
      height: 110px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      margin-bottom: 25px;
      .upload_add {
        font-size: 48px !important;
        margin-top: 30px;
      }
      .upload_txt {
        margin-top: 10px;
      }
    }
    .business_item {
      .el-form-item {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }
    .contract_file {
    }
    .license_num {
      .el-input-group__append {
        background: #2a82e4;
        .el-button {
          background: #2a82e4;
          color: #fff;
          height: 100%;
        }
      }
    }
  }
  :deep(.el-tabs) {
    margin-top: 17px;
    padding-left: 13px;
    .el-tabs__item {
      height: 26px;
      line-height: 26px;
    }
    .el-tabs__active-bar {
      width: 34px !important;
      left: 11px;
    }
  }
  .stadium_box {
    height: 630px;
  }
  .form_btn {
    display: flex;
    justify-content: center;
    margin-top: 23px;
    .el-button {
      width: 118px;
      height: 44px;
      line-height: 44px;
      padding: 0;
      font-size: 18px;
      & + .el-button {
        margin-left: 52px;
      }
    }
  }
}
:deep(.el-dialog) {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 29px 0 51px;
  }
  .dialog_tip {
    text-align: center;
    img {
      width: 99px;
      height: 100px;
    }
    p {
      font-size: 24px;
      line-height: 35px;
      color: #383838;
      margin: 9px 0;
    }
    span {
      font-size: 16px;
      line-height: 24px;
      color: #a6a6a6;
      display: block;
    }
    .el-button {
      width: 77px;
      height: 39px;
      line-height: 39px;
      padding: 0;
      margin-top: 18px;
      border: 1px solid #a6a6a6;
      color: #a6a6a6;
      font-size: 20px;
      border-radius: 10px;
    }
    .el-button:hover,
    .el-button:focus {
      border-color: #a6a6a6;
      color: #a6a6a6;
      background: none;
    }
  }
}
</style>
